const addEventListener = EventTarget.prototype.addEventListener

const createHTMLEvent = function(type) {
  const event = document.createEvent('HTMLEvents')
  event.initEvent(type)
  return event
}

export const EventListenerWrapper = function addEventListenerWrapper(type) {
  if (type === 'resize') {
    registerEvent(this)
  }
  // 覆盖其他事件
  addEventListener.apply(this, arguments)
}
// new ResizeObserver
function initObserver(callback) {
  const observer = (initObserver.observer = initObserver.observer || new ResizeObserver(callback))
  observer.initialized = true

  return observer
}

function registerEvent(elm) {
  // ResizeObserver监听dom大小的变化
  const observer = initObserver(entries => {
    if (observer.initialized) {
      observer.initialized = false
      return
    }
    // 多个元素都触发resize事件
    for (let entry of entries) {
      const event = createHTMLEvent('resize')
      // dom元素派发事件
      entry.target.dispatchEvent(event)
      // dom属性派发
      if (entry && entry.target && typeof entry.target.onresize === 'function') {
        entry.target.onresize(event)
      }
    }
  })

  observer.observe(elm)
}
// 重写dom元素的addEventListener方法
HTMLElement.prototype.addEventListener = EventListenerWrapper

// dom元素的onresize事件
Reflect.defineProperty(HTMLElement.prototype, 'onresize', {
  set(handler) {
    this._onresize = handler
    if (typeof handler !== 'function') {
      return
    }
    registerEvent(this)
  },
  get() {
    return this._onresize || null
  }
})
